//
//  TTShopCartView.m
//  TaoTuo
//
//  Created by admin on 2019/8/23.
//  Copyright © 2019 admin. All rights reserved.
//

#import "TTShopCartView.h"

@interface TTShopCartView ()

@property (nonatomic, strong) UIImageView *imageView;
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) UILabel *countLabel;
@property (nonatomic, copy) ClickShopCartBlock shopCartBlock;

@end

@implementation TTShopCartView

- (instancetype)initWithFrame:(CGRect)frame imageName:(NSString *)imageName title:(NSString *)title clickShopCartBlock:(nonnull ClickShopCartBlock)shopCartBlock
{
    self = [super initWithFrame:frame];
    if (self) {
        
        self.shopCartBlock = shopCartBlock;
        self.imageView.image = [UIImage imageNamed:imageName];
        self.titleLabel.text = title;
        if (title.length > 0) {
            self.imageView.frame = CGRectMake(0, 0, self.width, self.height * 0.7);
            self.titleLabel.frame = CGRectMake(0, self.imageView.bottom, self.width, self.height - self.imageView.height);
        } else {
            self.imageView.frame = self.bounds;
            self.titleLabel.frame = CGRectZero;
        }
        
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction)];
        [self addGestureRecognizer:tap];
        
    }
    return self;
}


- (void)tapAction
{
    if (self.shopCartBlock) {
        self.shopCartBlock(self);
    }
}

- (void)setCount:(int)count
{
    _count = count;
    
    self.countLabel.hidden = count == 0;
    
    if (count == 0) return;
    
    self.countLabel.text = [NSString stringWithFormat:@"%d", count];
    CGFloat w = [self.countLabel.text boundingRectWithSize:CGSizeMake(MAXFLOAT, 18) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:12]} context:nil].size.width + 10;
    if (w > 40) {
        w = 40;
    } else if (w < self.countLabel.height) {
        w = self.countLabel.height;
    }
    self.countLabel.width = w;
    self.countLabel.layer.cornerRadius = 7.5;
    
}

- (UIImageView *)imageView
{
    if (!_imageView) {
        _imageView = [[UIImageView alloc] init];
        _imageView.contentMode = UIViewContentModeCenter;
        [self addSubview:_imageView];
    }
    return _imageView;
}

- (UILabel *)titleLabel
{
    if (!_titleLabel) {
        _titleLabel = [UILabel labelTextCenterWithTitle:@"" color:UIColorHex(666666) fontSize:10];
        [self addSubview:_titleLabel];
    }
    return _titleLabel;
}

- (UILabel *)countLabel
{
    if (!_countLabel) {
        
        _countLabel = [UILabel labelTextCenterWithTitle:@"" color:[UIColor whiteColor] fontSize:10];
        _countLabel.frame = CGRectMake(self.centerX - self.left, 0, 0, 15);
        _countLabel.layer.backgroundColor = [UIColor redColor].CGColor;
        [self addSubview:_countLabel];
    }
    return _countLabel;
}

@end
